package wx.event.controller;


import org.springframework.web.bind.annotation.RestController;
import wx.event.entity.weixing.WxEventRequest;
import wx.event.entity.weixing.WxRequest;
import wx.event.impl.core.ProcessFactory;
import wx.event.utils.SignUtil;
import wx.event.utils.XMLUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信公众平台->基本配置->服务器配置->服务器url中的方法
 * @author why
 * time 2018年6月29日16:28:20
 */
@RestController
public class WxController {
    public void WxService(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        WxRequest wxRequest = new WxRequest(request);
        if (SignUtil.checkSignature(wxRequest.getSignature(), wxRequest.getTimestamp(), wxRequest.getNonce())){
            PrintWriter out = response.getWriter();
            if (request.getMethod().toLowerCase().equals("get")){
                //验证请求是否来自微信服务器
                out.print(wxRequest.getEchostr());
            }else{
                //处理请求
                out.print(processEvent(request));
            }
        }
    }

    /**
     * 处理请求
     * @param request
     * @return
     */
    private static String processEvent(HttpServletRequest request) throws Exception {
        //处理请求参数
        Map<String, String> requestMap = XMLUtil.parseXml(request);
        WxEventRequest wxEventRequest = new WxEventRequest(requestMap);
        //返回结果到用户微信
        return new ProcessFactory(wxEventRequest).getResult();
    }
}
